package com.wanlian.candy.controller;

import com.wanlian.candy.controller.session.UserSessionInfo;
import com.wanlian.common.ConstantCode;
import com.wanlian.entity.Device;
import com.wanlian.entity.Storage;
import com.wanlian.entity.StorageItem;
import com.wanlian.entity.User;
import com.wanlian.error.ErrorCode;
import com.wanlian.json.JsonResult;
import com.wanlian.json.JsonStringUtil;
import com.wanlian.model.ResultModel;
import com.wanlian.netty.File.model.FileDeleteModel;
import com.wanlian.netty.File.model.FileRenameModel;
import com.wanlian.service.DeviceServices;
import com.wanlian.service.StorageServices;
import com.wanlian.util.HttpUtils;
import com.wanlian.vo.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;


/**
 * 用户完成任务时，可以获取积分或者int
 */
@Controller
@RequestMapping("/storage")
public class StorageController {

    @Autowired
    private StorageServices storageServices;

    @Autowired
    private DeviceServices deviceServices;

    /**
     * 用户绑定设备添加新云盘
     *
     * @return
     */
    @RequestMapping(value = "/add", method = {RequestMethod.POST}, produces = "application/json")
    @ResponseBody
    public String add(HttpSession session) {
        UserSessionInfo usersessionInfo = (UserSessionInfo) session.getAttribute(ConstantCode.USERINFO_KEY);
        if (usersessionInfo == null) {
            return new JsonResult().Serailze(false, ErrorCode.ERROR_SESSION_TAG, ErrorCode.USER_SESSION_NOT_TIME);
        }
        User loginUser = usersessionInfo.getLoginUser();
        Device device = deviceServices.queryDeviceByUserId(loginUser.getId());
        if (device == null) {
            return new JsonResult().Serailze(new ResultModel(false, ErrorCode.DEVICE_USER_NOT_EXIST));
        }
        ResultModel resultModel1 = storageServices.queryStorageByUserId(loginUser.getId(), device.getDeviceId());
        Storage storage = (Storage) resultModel1.getObject();
        ResultModel resultModel = new ResultModel();
        if (storage == null) {
            storage = new Storage();
            storage.setUserId(loginUser.getId());
            storage.setDeviceId(device.getDeviceId());
            resultModel = storageServices.doAdd(storage);
        } else {
            resultModel.setBresult(false);
            resultModel.setMessage(ErrorCode.STORAGE_USER_EXISTS);
        }
        return new JsonResult().Serailze(resultModel);
    }

    /**
     * 添加云盘项（电影，照片，音乐）
     *
     * @param data
     * @return
     */
    @RequestMapping(value = "/item/add", method = {RequestMethod.POST}, produces = "application/json")
    @ResponseBody
    public String addItem(@RequestBody String data) {
        ResultModel resultModel = new ResultModel();
        Device device = new Device();
        if (device == null) {
            return new JsonResult().Serailze(new ResultModel(false, ErrorCode.DEVICE_USER_NOT_EXIST));
        }
        Storage storage = storageServices.queryStorageByDId(device.getDeviceId());
        if (storage != null) {
            StorageItem item = JsonStringUtil.readValue(data, StorageItem.class);
            if (item.getFileType() > 3) {
                return new JsonResult().Serailze(false, ErrorCode.STORAGEITEM_ADD_DEF);
            }

            item.setStorageId(storage.getId());
            resultModel = storageServices.doAddItem(item);
        }
        return new JsonResult().Serailze(resultModel);

    }

    /**
     * 编辑修改云盘信息
     *
     * @param data
     * @return
     */
    @RequestMapping(value = "/edit", method = {RequestMethod.POST}, produces = "application/json")
    @ResponseBody
    public String edit(@RequestBody String data, HttpSession session) {
        UserSessionInfo usersessionInfo = (UserSessionInfo) session.getAttribute(ConstantCode.USERINFO_KEY);
        if (usersessionInfo != null && usersessionInfo.getLoginUser() != null) {
            User loginUser = usersessionInfo.getLoginUser();
            Device device = deviceServices.queryDeviceByUserId(loginUser.getId());
            if (device == null) {
                return new JsonResult().Serailze(new ResultModel(false, ErrorCode.DEVICE_USER_NOT_EXIST));
            }
            ResultModel resultModel1 = storageServices.queryStorageByUserId(loginUser.getId(), device.getDeviceId());
            Storage storage = (Storage) resultModel1.getObject();
            Storage udstorage = JsonStringUtil.readValue(data, Storage.class);
            storage.setTotal(udstorage.getTotal());
            ResultModel resultModel = storageServices.doEdit(storage);
            return new JsonResult().Serailze(resultModel);
        } else {
            return new JsonResult().Serailze(false, ErrorCode.ERROR_SESSION_TAG, ErrorCode.USER_SESSION_NOT_TIME);
        }
    }

    /**
     * 编辑修改云盘项
     *
     * @param data
     * @return
     */
    @RequestMapping(value = "/item/edit", method = {RequestMethod.POST}, produces = "application/json")
    @ResponseBody
    public String editItem(@RequestBody String data) {
        StorageItem storageItem = JsonStringUtil.readValue(data, StorageItem.class);
        StorageItem storageItem1 = storageServices.queryStorageItemById(storageItem.getId());
        if (storageItem1 == null) {
            return new JsonResult().Serailze(false, ErrorCode.STORAGE_SEARCH_DEF);
        }
        storageItem1.setFileName(storageItem.getFileName());
        ResultModel resultModel = storageServices.doEditItem(storageItem1);
        return new JsonResult().Serailze(resultModel);
    }

    /**
     * 根据用户获取该用户的云盘信息
     *
     * @return
     */
    @RequestMapping(value = "/device/{key}", method = {RequestMethod.POST}, produces = "application/json")
    @ResponseBody
    public String queryByKey(@PathVariable("key") String key) {
        Device device = deviceServices.queryByDeviceKey(key);
        if (device == null) {
            return new JsonResult().Serailze(new ResultModel(false, ErrorCode.DEVICE_USER_NOT_EXIST));
        }
        ResultModel resultModel = storageServices.queryStorageByUserId(device.getUserid(), device.getDeviceId());
        return new JsonResult().Serailze(resultModel);
    }

    /**
     * 根据用户ID查询云盘下的所有云盘项
     *
     * @param data
     * @return
     */
    @RequestMapping(value = "/item/id", method = {RequestMethod.POST}, produces = "application/json")
    @ResponseBody
    public String queryItemsByStorageId(@RequestBody String data, HttpSession session) {
        Page page = JsonStringUtil.readValue(data, Page.class);
        UserSessionInfo userSessionInfo = (UserSessionInfo) session.getAttribute(ConstantCode.USERINFO_KEY);
        User loginUser = userSessionInfo.getLoginUser();
        ResultModel resultModel = new ResultModel();
        if (userSessionInfo != null && userSessionInfo.getLoginUser() != null) {
            Device device = deviceServices.queryDeviceByUserId(userSessionInfo.getLoginUser().getId());
            if (device == null) {
                return new JsonResult().Serailze(new ResultModel(false, ErrorCode.DEVICE_USER_NOT_EXIST));
            }
            ResultModel resultModel1 = storageServices.queryStorageByUserId(loginUser.getId(), device.getDeviceId());
            Storage storage = (Storage) resultModel1.getObject();
            if (storage != null) {
                resultModel = storageServices.queryItemsByStorageId(storage.getId(), page);
            } else {
                resultModel.setBresult(false);
                resultModel.setMessage(ErrorCode.STORAGE_NOT_EXISTS);
            }
        } else {
            return new JsonResult().Serailze(false, ErrorCode.ERROR_SESSION_TAG, ErrorCode.USER_SESSION_NOT_TIME);
        }
        return new JsonResult().Serailze(resultModel);
    }

    /**
     * 根据云盘ID和文件类型查询响应数据
     *
     * @param type
     * @return
     */
    @RequestMapping(value = "/item/type/{type}", method = {RequestMethod.POST}, produces = "application/json")
    @ResponseBody
    public String queryItemsByStorageIdAndFileType(@PathVariable int type, HttpSession session) {
        UserSessionInfo userSessionInfo = (UserSessionInfo) session.getAttribute(ConstantCode.USERINFO_KEY);
        if (userSessionInfo == null) {
            return new JsonResult().Serailze(false, ErrorCode.ERROR_SESSION_TAG, ErrorCode.USER_SESSION_NOT_TIME);
        } else {
            Device device = deviceServices.queryDeviceByUserId(userSessionInfo.getLoginUser().getId());
            if (device != null) {
                Storage storage = storageServices.queryStorageByDId(device.getDeviceId());
                ResultModel model = storageServices.queryItemsByStorageIdAndFileType(storage.getId(), type);
                return new JsonResult().Serailze(model);
            }
        }
        return new JsonResult().Serailze(false, "参数异常");
    }


    /**
     * 根据云盘ID和文件类型查询响应数据
     *
     * @param type
     * @return
     */
    @RequestMapping(value = "/item/type/{type}/{deviceKey}", method = {RequestMethod.POST}, produces = "application/json")
    @ResponseBody
    public String queryItemsByFileType(@PathVariable(value = "type") int type, @PathVariable(value = "deviceKey") String deviceKey) {
        Device device = deviceServices.queryByDeviceKey(deviceKey);
        if (device != null) {
            Storage storage = storageServices.queryStorageByDId(device.getDeviceId());
            ResultModel model = storageServices.queryItemsByStorageIdAndFileType(storage.getId(), type);
            return new JsonResult().Serailze(model);
        }
        return new JsonResult().Serailze(false, "参数异常");
    }


    @RequestMapping(value = "/item/delete")
    @ResponseBody
    public String doDeleteStorageItem(@RequestParam("key") String deviceKey,@RequestParam("filepath") String filepath) {
        FileDeleteModel fileDeleteModel=new FileDeleteModel();
        fileDeleteModel.setDeviceKey(deviceKey);
        fileDeleteModel.setFilePath(filepath);
        HttpUtils.sendPost("http://localhost:8003/wanlian.fileupload/file/delete", JsonStringUtil.writeValueAsString(fileDeleteModel));
        return new JsonResult().Serailze(true, "文件删除成功");
    }


    @RequestMapping(value = "/item/rename")
    @ResponseBody
    public String renameStorageItem(@RequestParam("key")String key,@RequestParam("src")String src,@RequestParam("dst")String dst) {
        FileRenameModel fileRenameModel=new FileRenameModel();
        fileRenameModel.setDeviceKey(key);
        fileRenameModel.setSrcFileName(src);
        fileRenameModel.setDstFileName(dst);
        HttpUtils.sendPost("http://localhost:8003/wanlian.fileupload/file/rename", JsonStringUtil.writeValueAsString(fileRenameModel));
        return new JsonResult().Serailze(true, "文件重命名成功");
    }


    /**
     * 查询云盘子项
     *
     * @param data
     * @return
     */
    @RequestMapping(value = "/item/query", method = {RequestMethod.POST}, produces = "application/json")
    @ResponseBody
    public String queryStorageItem(@RequestBody String data) {
        StorageItem storageItem = JsonStringUtil.readValue(data, StorageItem.class);
        StorageItem storageItem1 = storageServices.queryStorageItemById(storageItem.getId());
        ResultModel resultModel = new ResultModel();
        if (storageItem1 != null) {
            resultModel.setBresult(true);
            resultModel.setObject(storageItem1);
        } else {
            resultModel.setBresult(false);
            resultModel.setMessage(ErrorCode.STORAGE_SEARCH_DEF);
        }
        return new JsonResult().Serailze(resultModel);
    }
}